--Inport: PMEngine, PrivateDB, ProfileDB, GlobalDB
local PMEngine, L, PrivateDB, ProfileDB, GlobalDB = unpack(select(2, ...)); 
local CB = PMEngine:NewModule('CastBars')
PMEngine.CB = CB
local media = LibStub("LibSharedMedia-3.0")
local db

----------------------------
-- Upvalues
-- GLOBALS: LibStub, QuartzDB
local type, pairs, tonumber = type, pairs, tonumber

local defaults = {
	profile = {
		--modules = { ["*"] = true, ["EnemyCasts"] = false },
		--hidesamwise = true,
		sparkcolor = {1, 1, 1, 0.5},
		spelltextcolor = {0, 0, 0},
		timetextcolor = {1, 1, 1},
		castingcolor = {1.0, 0.49, 0},
		channelingcolor = {0.32, 0.3, 1},
		completecolor = {0.12, 0.86, 0.15},
		failcolor = {1.0, 0.09, 0},
		backgroundcolor = {0, 0, 0},
		bordercolor = {0, 0, 0},
		backgroundalpha = 1,
		borderalpha = 1,
		casttimeprecision = 1,
	},
}

function CB:Merge(source, target)
	local final
	if type(target) ~= "table" then 
		final = {} 
	else
		final = {} 
		for a, b in pairs(target) do
			final[a] = b
		end
	end
	for k,v in pairs(source) do
		if type(v) == "table" then
			final[k] = self:Merge(v, final[k])
		elseif not final[k] then
			final[k] = v
		end
	end
	return final
end

CB.Util = {}
function CB.Util.TimeFormat(num, isCastTime)
	if num <= 10 or (isCastTime and num <= 60) then
		return ("%%.%df"):format(db.casttimeprecision), num
	elseif num <= 60 then
		return "%d", num
	elseif num <= 3600 then
		return "%d:%02d", num / 60, num % 60
	else
		return "%d:%02d", num / 3600, (num % 3600) / 60
	end
end

function CB:ToggleLock(showUI)
	local func = self.unlock and "Lock" or "Unlock"
	self[func](self, showUI)
end

function CB:Unlock(showUI)
	self.unlock = true

	if PMEngine.db.castbars.modules.Player then self.Player:Unlock() end
	if PMEngine.db.castbars.modules.Target then self.Target:Unlock() end
	if PMEngine.db.castbars.modules.Focus then self.Focus:Unlock() end

	if showUI then
		self:ShowUnlockDialog()
	end
end

function CB:Lock()
	self.unlock = nil
	if PMEngine.db.castbars.modules.Player then self.Player:Lock() end
	if PMEngine.db.castbars.modules.Target then self.Target:Lock() end
	if PMEngine.db.castbars.modules.Focus then self.Focus:Lock() end
	if self.unlock_dialog then self.unlock_dialog:Hide() end
end

function CB:ShowUnlockDialog()
	if not self.unlock_dialog then
		local f = CreateFrame("Frame", "CastBarUnlockDialog", UIParent)
		f:SetFrameStrata("DIALOG")
		f:SetToplevel(true)
		f:EnableMouse(true)
		f:SetClampedToScreen(true)
		f:SetWidth(360)
		f:SetHeight(110)
		f:CreateBackdrop('Transparent')
		--[[f:SetBackdrop{
			bgFile="Interface\\DialogFrame\\UI-DialogBox-Background" ,
			edgeFile="Interface\\DialogFrame\\UI-DialogBox-Border",
			tile = true,
			insets = {left = 11, right = 12, top = 12, bottom = 11},
			tileSize = 32,
			edgeSize = 32,
		}]]
		f:SetPoint("TOP", 0, -50)
		f:Hide()
		f:SetScript("OnShow", function() PlaySound("igMainMenuOption") end)
		f:SetScript("OnHide", function() PlaySound("gsTitleOptionExit") end)

		local tr = f:CreateTitleRegion()
		tr:SetAllPoints(f)

		local header = CreateFrame("Frame", "CastBarUnlockDialogHeader", CastBarUnlockDialog)
		header:CreateBackdrop()
		header:SetFrameStrata("DIALOG")
		header:SetFrameLevel(9)
		--header:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Header")
		header:SetWidth(200); header:SetHeight(30)
		header:SetPoint("TOP", 0, 12)

		local title = header:CreateFontString("ARTWORK")
		title:SetFontObject("GameFontNormal")
		title:SetPoint("CENTER", header, "CENTER", 0, 0)
		title:SetText("PandemoniuM UI Castbars")

		local desc = f:CreateFontString("ARTWORK")
		desc:SetFontObject("GameFontHighlight")
		desc:SetJustifyV("TOP")
		desc:SetJustifyH("LEFT")
		desc:SetPoint("TOPLEFT", 18, -32)
		desc:SetPoint("BOTTOMRIGHT", -18, 48)
		desc:SetText("Bars unlocked. Move them now and click Lock when you are done.")

		local lockBars = CreateFrame("CheckButton", "CastBarUnlockDialogLock", f, "OptionsButtonTemplate")
		getglobal(lockBars:GetName() .. "Text"):SetText("Lock")

		lockBars:SetScript("OnClick", function(self)
			CB:Lock()
			--LibStub("AceConfigRegistry-3.0"):NotifyChange("Quartz3")
		end)

		--position buttons
		lockBars:SetPoint("BOTTOMRIGHT", -14, 14)
		local S = PMEngine:GetModule('Skins')
		S:HandleButton(lockBars)

		self.unlock_dialog = f
	end
	self.unlock_dialog:Show()
end

local copyExclude = {
	x = true,
	y = true,
}

function CB:CopySettings(from, to)
	for k,v in pairs(from) do
		if to[k] and not copyExclude[k] and type(v) ~= "table" then
			to[k] = v
		end
	end
end

local function getBar(info)
	return CB.CastBarTemplate.bars[info]
end
function CB:ApplySettings()
	db = self.db

	if PMEngine.db.castbars.modules.Player then	
		CB.Player:UpdateDB()
		local player = getBar('PlayerCastBar')
		player:ApplySettings()
	end
	
	if PMEngine.db.castbars.modules.Latency then 
		CB.Latency:ApplySettings()
	end

	if PMEngine.db.castbars.modules.Target then	
		local target = getBar('TargetCastBar')
		target:ApplySettings()
	end
	if PMEngine.db.castbars.modules.Focus then 
		local focus = getBar('Focus')
		focus:ApplySettings()
	end
end

function CB:Initialize()
	CB.db = PMEngine.db.castbars
	db = self.db

	if PMEngine.db.castbars.modules.Player then CB.Player:Initialize()  end
	if PMEngine.db.castbars.modules.Target then CB.Target:Initialize()  end
	if PMEngine.db.castbars.modules.Focus then CB.Focus:Initialize()  end
	if PMEngine.db.castbars.modules.Latency then CB.Latency:Initialize()  end
end

PMEngine:RegisterModule(CB:GetName())